export default{
    namespaced:true,
    state:{
        // 购物车数组
        // cartList:[{name:'小米手机',num:100}]
        cartList:uni.getStorageSync("cartList") || []
    },
    getters:{
      // 购物车的商品总数量
      cartCount(state){
          let  count = 0;
          state.cartList.forEach((goods)=>{
            //   console.log(12,goods);
            count +=goods.num
          })
          return count
      },
      // 计算当前全选按钮是否要选中 =  数组里面的商品 是否都是 checked=true
      isAllChecked(state){
       return state.cartList.length && state.cartList.every(item=>item.checked)
      },
      checkedCartList(state){
        return state.cartList.filter(item=>item.checked)
      },
      // 计算要购买的数量
      totalCount(state,getters){
        let  totalCount = 0
        getters.checkedCartList.map(item=>totalCount+=item.num)
        return  totalCount
      },
      totalPrice(state,getters){
        let  totalPrice = 0
        getters.checkedCartList.map(item=>totalPrice+=item.goods_price)
        return  totalPrice
      }
    },
    mutations:{
     // 添加商品
     // payload= {value:当前要添加的商品对象 }
    cartAdd(state,payload){
        const index = state.cartList.findIndex(item=>item.goods_id=== payload.value.goods_id)

        if(index===-1){
            // 不存在
            state.cartList.push({...payload.value,num:1,checked: true})
        }else{
            // 存在 修改数组中元素的购买数量即可
            state.cartList[index].num++
        }
        // 缓存
        uni.setStorageSync('cartList',state.cartList);
          
    },

    // 单选框
    cartToggleCheck(state, payload){
     // 1 根据商品id找到对应的索引
       const index = state.cartList.findIndex(item=>item.goods_id == payload.value)
     // 2  取反 通过数组[下标].checked=!数组[下标].checked
     state.cartList[index].checked=!state.cartList[index].checked
      // 缓存
      uni.setStorageSync('cartList',state.cartList);
    },
    CartNumUpdate(state, payload){
      // 1 根据商品id找到对应的索引
      const index = state.cartList.findIndex(item=>item.goods_id == payload.value.goods_id)
        //   2 数组[index].num+=-1
        state.cartList[index].num += payload.value.unit
          // 3存一份到缓存中
         uni.setStorageSync("cartList", state.cartList)
    },
    cartItemDelete(state, payload){
         // 1 根据商品id找到对应的索引
       const index = state.cartList.findIndex(item=>item.goods_id == payload.value)
       //    2删除
       state.cartList.splice(index,1)
       // 3存一份到缓存中
       uni.setStorageSync("cartList", state.cartList)
    },
    cartAllToggle(state, payload){
      // 1取反
      const isAllChecked = !payload.value;
      state.cartList.forEach(goods => goods.checked = isAllChecked);
      uni.setStorageSync("cartList", state.cartList)

    }
       
    },
    actions:{}
}